package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsTopicMapper;
import com.qf.pojo.DtsTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class DtsTopicServiceImpl implements DtsTopicService {
    @Autowired
    private DtsTopicMapper topicMapper;

    @Override
    public IPage<DtsTopic> queryByPage(Integer page, Integer limit,
                                       Integer id, String title,
                                       String sort, String order) {
        IPage<DtsTopic> topicIPage = new Page<>(page, limit);
        QueryWrapper<DtsTopic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        if (!StringUtils.isEmpty(id)) {
            queryWrapper.eq("id", id);
        }
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }

        if ("asc".equalsIgnoreCase(order)) {
            queryWrapper.orderByAsc(sort);
        } else {
            queryWrapper.orderByDesc(sort);
        }
        IPage<DtsTopic> dtsTopicIPage = topicMapper.selectPage(topicIPage, queryWrapper);

        return dtsTopicIPage;
    }

    @Override
    public DtsTopic addOne(DtsTopic topic) {
        topic.setAddTime(new Date());
        topic.setDeleted(false);
        topic.setUpdateTime(new Date());
        int insert = topicMapper.insert(topic);
        if (insert == 0) {
            throw new RuntimeException("添加失败！");
        }
        return topic;
    }
}
